package main

import (
	"fmt"
	"io"
	"log"
	"net"
	"time"
	"zinxp/znet"
)

func main() {
	log.SetFlags(log.Lshortfile | log.LstdFlags)
	fmt.Println("Client Test ... start")

	conn, err := net.Dial("tcp", "127.0.0.1:7878")
	if err != nil {
		fmt.Println("client start err, exit!")
		return
	}

	for {
		dp := znet.NewDataPack()
		msgpack := znet.NewMsgPackage(0, []byte("Zinx 0.5 Client Test Message"))
		msg, _ := dp.Pack(msgpack)
		_, err := conn.Write(msg)
		if err != nil {
			fmt.Println("write error err ", err)
			return
		}

		//先读出流中的head部分
		headData := make([]byte, dp.GetHeadLen())
		_, err = io.ReadFull(conn, headData)
		if err != nil {
			log.Println("read head error ", err)
			return
		}
		msgHead, err := dp.Unpack(headData)
		if err != nil {
			log.Println("server unpack error ", err)
			return
		}
		if msgHead.GetDataLen() > 0 {
			//msg 是有data数据的，需要再次读取data数据
			msg := msgHead.(*znet.Message)
			msg.Data = make([]byte, msg.GetDataLen())
			_, err := io.ReadFull(conn, msg.Data)
			if err != nil {
				log.Println("server unpack data error ", err)
				return
			}
			fmt.Println("==>Recv Msg: ID=", msg.Id, " len=", msg.DataLen, " data=", string(msg.Data))
		}
		time.Sleep(time.Second)
	}
}
